from migration.base_migrator import BaseMigrator
from utils.common import CommonUtils
import os

class TriggerMigrator(BaseMigrator):
    def __init__(self, mysql_db, kingbase_db, migration_config, logger, task_name):
        super().__init__(mysql_db, kingbase_db, migration_config, logger, task_name)
        self.triggers_dir = os.path.join(self.reports_dir, 'triggers')
        CommonUtils.ensure_directory_exists(self.triggers_dir)
    
    def migrate_triggers(self):
        """
        迁移触发器
        注意：MySQL和PostgreSQL的触发器语法差异很大，这里提供基本支持
        """
        try:
            triggers = self.mysql_db.get_all_triggers()
            self.logger.info(f"共需要迁移 {len(triggers)} 个触发器")
            
            for trigger in triggers:
                trigger_name = trigger['TRIGGER_NAME']
                trigger_def = trigger['TRIGGER_DEFINITION']
                
                # 转换触发器SQL
                converted_trigger_sql = self.convert_trigger_sql(trigger_def, trigger)
                
                # 保存到文件
                trigger_file = os.path.join(self.triggers_dir, f"{trigger_name}_trigger.sql")
                CommonUtils.write_text_file(trigger_file, converted_trigger_sql)
                self.logger.info(f"触发器SQL导出成功: {trigger_file}")
            
        except Exception as e:
            self.logger.error(f"触发器迁移失败\n{e}")
    
    def convert_trigger_sql(self, mysql_trigger_sql, trigger_info):
        """
        将MySQL触发器SQL转换为PostgreSQL/KingbaseES兼容的触发器SQL
        """
        # 这里提供基本的触发器转换支持
        # 注意：MySQL和PostgreSQL的触发器语法差异很大，完整转换需要更复杂的逻辑
        
        trigger_name = trigger_info['TRIGGER_NAME']
        event_manipulation = trigger_info['EVENT_MANIPULATION']  # INSERT, UPDATE, DELETE
        event_object_table = trigger_info['EVENT_OBJECT_TABLE']
        action_timing = trigger_info['ACTION_TIMING']  # BEFORE, AFTER
        
        # 构建PostgreSQL触发器框架
        # 使用小写的模式名，与kingbase_db.py保持一致
        target_schema_lower = self.target_schema.lower()
        postgres_trigger_sql = f"""
-- 原始MySQL触发器: {trigger_name}
-- 注意：MySQL和PostgreSQL触发器语法差异很大，请手动检查和调整

-- 创建触发器函数
CREATE OR REPLACE FUNCTION {target_schema_lower}.trf_{trigger_name}()
RETURNS TRIGGER AS $$
BEGIN
-- 转换后的触发器逻辑
-- {mysql_trigger_sql}

-- 根据触发事件类型返回相应的值
IF TG_OP = 'INSERT' THEN
    RETURN NEW;
ELSIF TG_OP = 'UPDATE' THEN
    RETURN NEW;
ELSIF TG_OP = 'DELETE' THEN
    RETURN OLD;
END IF;

RETURN NULL;
END;
$$ LANGUAGE plpgsql;

-- 创建触发器
CREATE TRIGGER {trigger_name}
{action_timing} {event_manipulation} ON {target_schema_lower}.{event_object_table}
FOR EACH ROW EXECUTE FUNCTION {target_schema_lower}.trf_{trigger_name}();
"""
        
        return postgres_trigger_sql